package com.pclong.fightlandlordserver.service;

import com.pclong.fightlandlordserver.game.model.Player;
import com.pclong.fightlandlordserver.game.model.Room;
import com.pclong.fightlandlordserver.model.PlayerResult;
import com.pclong.fightlandlordserver.model.RoomResult;
import com.pclong.fightlandlordserver.util.ConvertUtil;
import com.pclong.fightlandlordserver.util.ModelUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import org.apache.mina.core.session.IoSession;
import org.hibernate.Query;
import org.hibernate.transform.ResultTransformer;

public class GamePlatformService extends F3SWebService<Object> {

    @Override
    public Class<?>[] getAliasTypes() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getNamedQuery() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getNamedQueryForCount() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ResultTransformer getResultTransformer() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void processQuerySetting(Query query, HttpServletRequest request) {
        // TODO Auto-generated method stub
    }

    /*
    /**
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String LOBBY_PLAYER_ADD(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"players":[{"name":"long","money":1000,"score":1000}]}
        return "{\"players\":[{\"name\":\"long\",\"money\":1000,\"score\":1000}]}";
    }

    /*
    /**
     * 大厅的信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String LOBBY_INFO_LIST(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"players":[{"name":"long","money":1000,"score":1000}]}
        return "{\"players\":[{\"name\":\"long\",\"money\":1000,\"score\":1000}]}";
    }
    /*
    /**
     * 获取玩家列表
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String LOBBY_PLAYER_LIST(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"players":[{"name":"long","money":1000,"score":1000}]}  
        String json = "{\"players\":[";
        int count = 0;
        PlayerResult playerRlt;
        for (IoSession ioSession : ModelUtil.getSessions()) {
            Player player = (Player) ioSession.getAttribute(Player.ATTR_NAME);
            if (player != null) {
                playerRlt = new PlayerResult(player.getId(), player.getName());
                playerRlt.setMoney(player.getPlayerProfile().getCurrentScore());
                playerRlt.setScore(player.getPlayerProfile().getCurrentScore());
                playerRlt.setPid(ConvertUtil.toInt(player.getPlayerProfile().getProfileId()));
                if (count == 0) {
                    json += gson.toJson(playerRlt);
                } else {
                    json += "," + gson.toJson(playerRlt);
                }
                count++;
            }
        }
        json += "]}";
        log.info("在线用户列表:" + json);
        return json;
//        return "{\"players\":[{\"name\":\"long\",\"money\":1000,\"score\":1000}]}";
    }
    /*
    /**
     * 房间中桌子的信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_ROOM_LIST(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String rid = request.getParameter("RID");
//        ModelUtil.getSessions();
        Map<String, Room> rooms = ModelUtil.getPlatform().getChild("1").getChildren();
        Room room;
        List<Room> roomsInQueue = new ArrayList<Room>();
        for (Room eachRoom : rooms.values()) {
            roomsInQueue.add(eachRoom);
        }
        Collections.sort(roomsInQueue, new Comparator<Room>() {

            public int compare(Room p1, Room p2) {
                if (ConvertUtil.toInt(p1.getId()) > ConvertUtil.toInt(p2.getId())) {
                    return 1;
                } else if (ConvertUtil.toInt(p1.getId()) < ConvertUtil.toInt(p2.getId())) {
                    return -1;
                }
                return 0;
            }
        });
        String json = "[";
        RoomResult roomRlt;
        PlayerResult playerRlt;
        String roomjson = "";
        int count = 0;
        for (int i = 0; i < roomsInQueue.size(); i++) {
            room = roomsInQueue.get(i);
            if (room != null) {
                roomjson = "{\"rid\": \"" + room.getId() + "\",\"rname\": \"" + room.getName() + "\",\"players\":{";
                int pcount = 0;
                for (Player player : room.getChildren().values()) {
                    playerRlt = new PlayerResult(player.getId(), player.getName());
                    playerRlt.setPid(ConvertUtil.toInt(player.getUserId()));
                    playerRlt.setAvatar(player.getAvatar());
                    playerRlt.setPos(String.valueOf(player.getPos()));
                    if (pcount != 0) {
                        roomjson += ",";
                    }
                    roomjson += "\"" + playerRlt.getPos() + "\":" + gson.toJson(playerRlt);
                    pcount++;
                }
                roomjson += "}}";
                if (count != 0) {
                    json += ",";
                }
                json += roomjson;

                count++;
            }
        }
        json += "]";
        log.info("房间列表信息:" + json);
        return json;
//        return "[{\"gid\":1,\"name\":\"1\",\"players\":{\"1\":{\"pid\":\"1\",\"nickname\":\"feng\",\"pos\":1,\"avatar\":\"../media/imageman.jpg\",\"ready\":true,\"score\":1000,\"money\":100}}},{\"gid\":2,\"name\":\"2\",\"players\":{\"1\":{\"pid\":\"2\",\"nickname\":\"yun\",\"pos\":1,\"avatar\":\"../media/imageman.jpg\",\"ready\":true,\"score\":1000,\"money\":100}}}]";
//        return "[{\"gid\":1,\"name\":\"1\",\"players\":[{\"pos\":1,\"avatar\":\"../media/imageman.jpg\",\"ready\":true,\"score\":1000,\"money\":100}]},{\"gid\":2,\"name\":\"2\",\"players\":[{\"pos\":1,\"avatar\":\"../media/imageman.jpg\",\"ready\":true,\"score\":1000,\"money\":100}]},{\"gid\":3,\"name\":\"1号桌\",\"players\":[{\"pos\":1,\"avatar\":\"../media/imageman.jpg\",\"ready\":true,\"score\":1000,\"money\":100}]}]";
    }
    /*
    /**
     * 加入房间
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_ROOM_JOIN(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = request.getParameter("userId");
        String roomid = request.getParameter("roomid");
        String pos = request.getParameter("pos");
        String json;
        Room room = ModelUtil.getPlatform().getChild("1").getChild(roomid);
        if (room != null) {
            if (room.getChild(pos) == null) {
                for (IoSession ioSession : ModelUtil.getSessions()) {
                    Player player = (Player) ioSession.getAttribute(Player.ATTR_NAME);
                    if (player != null && player.getId().equals(userId)) {
                        ((Player) ioSession.getAttribute(Player.ATTR_NAME)).setPos(ConvertUtil.toInt(pos));
                        ((Player) ioSession.getAttribute(Player.ATTR_NAME)).setParent(room);
                        ModelUtil.getPlatform().getChild("1").getChild(roomid).addChild(pos, (Player) ioSession.getAttribute(Player.ATTR_NAME));
                        break;
                    }
                }
                json = "{\"rid\":" + roomid + ",\"pos\":" + pos + "}";
            } else {
                json = "{\"success\":false,\"message\":\"pos have player\"}";
            }
        } else {
            json = "{\"success\":false,\"message\":\"room not find\"}";
        }
        log.info("用户加入房间：" + json);
        return json;
    }
    /*
    /**
     * 房间配置
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_ROOM_VIEWSTETING(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}"roomid":param1, "pos":p, "getPlayers" success false
//        String userId = request.getParameter("userId");
        String roomid = request.getParameter("roomid");
        String pos = request.getParameter("pos");
        String json;
        int count = 0;
        Room room = ModelUtil.getPlatform().getChild("1").getChild(roomid);
        if (room != null) {
            json = "{\"rid\":" + roomid + "}";
//            json = "{\"rid\":" + roomid + ",\"players\":[";
//            Set<String> players = room.getChildren().keySet();
//            Player player;
//            for (String p : players) {
//                player = room.getChildren().get(p);
//                if (count == 0) {
//                    json += "{\"pid\":" + player.getPlayerProfile().getProfileId() + ",\"pos\":" + p + "}";
//                } else {
//                    json += ",{\"pid\":" + player.getPlayerProfile().getProfileId() + ",\"pos\":" + p + "}";
//                }
//            }
//
//            json += "]}";
        } else {
            json = "{\"success\":false,\"message\":\"room not find\"}";
        }
        log.info("GAME_ROOM_VIEWSTETING:" + json);
        return json;
//        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }

    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String GAME_ROOM_UPDATE(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}"roomid":param1, "pos":p, "getPlayers" success false
//        String userId = request.getParameter("userId");
        String roomid = request.getParameter("roomid");
        String pos = request.getParameter("pos");
        String json;
        int count = 0;
        Room room = ModelUtil.getPlatform().getChild("1").getChild(roomid);
        if (room != null) {
//             json = "{\"rid\":" + roomid+"}";
            json = "{\"rid\":" + roomid + ",\"players\":{";
            Set<String> players = room.getChildren().keySet();
            Player player;
            for (String p : players) {
                player = room.getChildren().get(p);
                if (count != 0) {
                    json += ",";
                }
                json += "\"" + player.getPos() + "\":{\"pid\":\"" + player.getPlayerProfile().getProfileId() + "\",\"pos\":" + player.getPos() + ",\"name\":\"" + player.getName() + "\"";
                json += ",\"score\":" + player.getScore();
                json += ",\"money\":" + player.getMoney();
                json += ",\"avatar\":\"" + player.getAvatar() + "\"";
                json += ",\"ready\":" + player.isReady();
                json += "}";
                count++;
            }

            json += "}}";
        } else {
            json = "{\"success\":false,\"message\":\"room not find\"}";
        }
        log.info("房间用户信息：" + json);
        return json;
    }
    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_ROOM_ADD(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }
    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_INDEX_IDENTITY(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }
    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_ROOM_REMOVE(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = request.getParameter("userId");
        String roomid = request.getParameter("roomid");
        String pos = request.getParameter("pos");
        String json;
        Room room = ModelUtil.getPlatform().getChild("1").getChild(roomid);
        if (room != null) {
            Player player = room.getChild(pos);
            if (player != null) {
                player.setParent(null);
                ModelUtil.getPlatform().getChild("1").getChild(roomid).removeChild(pos);
                json = "{\"rid\":" + roomid + ",\"pos\":" + pos + "}";
            } else {
                json = "{\"success\":false,\"message\":\"pos have not player\"}";
            }
        } else {
            json = "{\"success\":false,\"message\":\"room not find\"}";
        }
        log.info(json);
        return json;
    }
    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_ROOM_EXIT(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = request.getParameter("userId");
        String roomid = request.getParameter("roomid");
        String pos = request.getParameter("pos");
        String json;
        Room room = ModelUtil.getPlatform().getChild("1").getChild(roomid);
        if (room != null) {
            Player player = room.getChild(pos);
            if (player != null) {
                player.setParent(null);
                ModelUtil.getPlatform().getChild("1").getChild(roomid).removeChild(pos);
//                for (IoSession ioSession : ModelUtil.getSessions()) {
//                    Player player = (Player) ioSession.getAttribute(Player.ATTR_NAME);                   
//                    if (player != null && player.getId().equals(userId)) {
//                        player.setPos(ConvertUtil.toInt(pos));
//                        player.setParent(room);
//                        ModelUtil.getPlatform().getChild("1").getChild(roomid).addChild(pos, player);
//                        break;
//                    }
//                }
                json = "{\"rid\":" + roomid + ",\"pos\":" + pos + "}";
            } else {
                json = "{\"success\":false,\"message\":\"pos have not player\"}";
            }
        } else {
            json = "{\"success\":false,\"message\":\"room not find\"}";
        }
        log.info("用户退出房间:" + json);
        return json;
    }
    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_FRIEND_INVITE(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }
    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String GAME_ROOM_KICK(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }

    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String GAME_ROOM_AUTOADD(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }
    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String LOBBY_PLAYER_REMOVE(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }
    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public String DEFAULT_ACCOUNT_IDENTITY(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }

    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String GAME_ROOM_CREATE(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }

    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String GAME_FRIEND_ONLINELIST(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }

    /*
    /**
     * 没有开始游戏之前，更新房间信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String GAME_FRIEND_LIST(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //{"rid":1}
        return "{\"rid\":1,\"players\":[{\"pid\":1,\"pos\":1},{\"pid\":2,\"pos\":2}]}";
    }
}
